import React, { PureComponent, Fragment } from 'react';
import { Form, Modal, Input, Select, Switch, TreeSelect} from 'antd';
const FormItem = Form.Item;
const TreeNode = TreeSelect.TreeNode;
const tree_icon = {
  all: require("@/assets/org_all.png"),
  company: require("@/assets/org_company.png"),
  team: require("@/assets/org_team.gif"),
}
class CustomizedForm extends PureComponent {
  constructor(props) {
    super(props);
    this.state = {
      allRoles: {},
      record: {},
      treeData:[],
      TreeValue:{}
    };
  }
  componentDidMount() {
    const { modalValue } = this.props;
    var data = {}
    if (modalValue.record && Object.keys(modalValue.record).length){
      data = {
        orgId: modalValue.record.orgId,
        orgName: modalValue.record.orgName
      }
    }
    this.setState({
      allRoles: modalValue.allRoles || {},
      treeData: modalValue.orgMenuList || {},
      record: modalValue.record || {},
      TreeValue:data
    });
  }
  onChange = (checkedList, item) => {
    const { allRules } = this.state;
    const backup = allRules;
    backup.roleRules[item].defaultValue = checkedList;
    this.setState({
      allRules: backup,
    });
  };
  /**
   * 异步数
   */
  onTreeChange = (value, label, extra) => {
    var data = {
      orgName:label[0],
      orgId:value,
      reset:true
    }
    this.setState({
      TreeValue: data
    })
  }
  onLoadData = treeNode => new Promise((resolve) => {
    const { dispatch } = this.props
    if (treeNode.props.children) {
      resolve();
      return;
    }
    dispatch({
      type: "system/fetchOrganize",
      payload: {
        menuId: treeNode.props.dataRef.id
      },
      callback: (res) => {
        treeNode.props.dataRef.children = res.orgMenuList
        this.setState({
          treeData: [...this.state.treeData],
        });
        resolve();
      }
    })
  })
  renderTreeNodes = data => data.map((item) => {
    if (item.children) {
      return (
        <TreeNode {...item} title={item.name} key={item.id} dataRef={item} icon={<img src={item.orgType == 1 ? tree_icon.company : tree_icon.team} />}>
          {this.renderTreeNodes(item.children)}
        </TreeNode>
      );
    }
    if (Object.keys(item).length == 0) return
    return <TreeNode {...item} title={item.name} key={item.id} dataRef={item} isLeaf={item.leaf ? false : true} icon={<img src={item.orgType == 1 ? tree_icon.company : tree_icon.team} />} />;

  })
  render() {
    const { modalVisible, handleUpdateModalVisible, handleUpdate, form } = this.props;
    const { allRoles, record, treeData, TreeValue} = this.state;
    const okHandle = () => {
      form.validateFields((err, fieldsValue) => {
        if (err) return;
        let data = {
          ...fieldsValue,
          inUse: fieldsValue.inUse ? 0 : 1,
          orgName: TreeValue.orgName,
          orgId: TreeValue.orgId,
        };;
        
        form.resetFields()
        if (record.hasOwnProperty('id')) {
          data.id = record.id;
          handleUpdate(data);
        } else {
          handleUpdate(data);
        }
        console.log(data)
      });
    };
    return (
      <Modal
        destroyOnClose //关闭时销毁 Modal 里的子元素
        title={record.userName || '新增帐号'}
        visible={modalVisible}
        // width={570}
        onOk={okHandle}
        onCancel={() => handleUpdateModalVisible()}
      >
        <Fragment>
          <Form style={{ marginBottom: 15 }}>
            <FormItem label="用户名称" labelCol={{ span: 5 }} wrapperCol={{ span: 15 }}>
              {form.getFieldDecorator('userName', {
                initialValue: record.userName || '',
                rules: [{ required: true, message: '请填写用户名称！' }],
              })(<Input autoComplete="off" />)}
            </FormItem>
            <FormItem label="用户昵称" labelCol={{ span: 5 }} wrapperCol={{ span: 15 }}>
              {form.getFieldDecorator('nickName', {
                initialValue: record.nickName || '',
                rules: [{ required: true, message: '请填写用户昵称！' }],
              })(<Input autoComplete="off" />)}
            </FormItem>
            <FormItem label="用户密码" labelCol={{ span: 5 }} wrapperCol={{ span: 15 }}>
              {form.getFieldDecorator('password', {
                initialValue: record.password || '',
                rules: [{ required: true, message: '请填写用户密码！' }],
              })(<Input autoComplete="off" />)}
            </FormItem>
            <FormItem label="用户厂商" labelCol={{ span: 5 }} wrapperCol={{ span: 15 }}>
              {form.getFieldDecorator('producer', {
                initialValue: record.producer || '',
                rules: [{ required: true, message: '请填写用户所属厂商！' }],
              })(<Input autoComplete="off" />)}
            </FormItem>
            {allRoles && Object.keys(allRoles).length ? (
              <FormItem label="选择角色" labelCol={{ span: 5 }} wrapperCol={{ span: 15 }}>
                {form.getFieldDecorator('role', {
                  initialValue: record.role || '',
                  rules: [{ required: true, message: '请选择用户角色！' }],
                })(
                  <Select>
                    {allRoles.map(item => {
                      return (
                        <Select.Option value={item.id} key={item.id}>
                          {item.roleName}
                        </Select.Option>
                      );
                    })}
                  </Select>
                )}
              </FormItem>
            ) : null}
            {treeData && Object.keys(treeData).length ? (
              <FormItem label="选择组织" labelCol={{ span: 5 }} wrapperCol={{ span: 15 }}>
                {form.getFieldDecorator('orgId', {
                  initialValue: record.orgName || '',
                  rules: [{ required: true, message: '请选择组织！' }],
                })(
                  <TreeSelect
                    // value={this.state.value}
                    showIcon={true}
                    loadData={this.onLoadData}
                    style={{ width: 300 }}
                    dropdownStyle={{ maxHeight: 400, overflow: 'auto' }}
                    placeholder="Please select"
                    onChange={this.onTreeChange}
                    allowClear
                  >
                    {this.renderTreeNodes(treeData)}
                  </TreeSelect>
                )}
              </FormItem>
            ) : null}
            <FormItem label="是否启用" labelCol={{ span: 5 }} wrapperCol={{ span: 15 }}>
              {form.getFieldDecorator('inUse', {
                initialValue: record.inUse ? false : true,
                valuePropName: 'checked',
              })(<Switch checkedChildren="启" unCheckedChildren="禁" />)}
            </FormItem>
          </Form>
        </Fragment>
      </Modal>
    );
  }
}

const EditorForm = Form.create()(CustomizedForm);
export default EditorForm;
